import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/utils/toast_utils.dart';

class SetPwdPage extends StatefulWidget {
  final String phone;
  final String type;

  const SetPwdPage(this.phone, {this.type});

  @override
  _SetPwdPageState createState() => _SetPwdPageState();
}

class _SetPwdPageState extends State<SetPwdPage> {
  final _formKey = GlobalKey<FormState>();
  String _password, _oldPwd;
  var pwdController = TextEditingController();
  var oldController = TextEditingController();
  String title = "重置登录密码";
  TextInputType textInputType = TextInputType.text;
  int maxLength = 12;

  @override
  void initState() {
    super.initState();
    if (null != widget.type) {
      switch (widget.type) {
        case "xgmm":
        case "wjmm":
          title = "重置登录密码";
          break;
        case "bdzf":
          title = "设置支付密码";
          textInputType = TextInputType.number;
          maxLength = 6;
          break;
        case "xgzf":
          title = "修改支付密码";
          textInputType = TextInputType.number;
          maxLength = 6;
          break;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 1.0,
        backgroundColor: Theme.of(context).canvasColor,
        titleSpacing: 0.0,
        centerTitle: true,
        title: Text(title, style: TextStyle(fontSize: 18)),
      ),
      body: Form(
        key: _formKey,
        child: ListView(
            padding: EdgeInsets.symmetric(horizontal: 22.0),
            children: <Widget>[
              Offstage(
                  offstage: widget.type != 'xgzf', child: SizedBox(height: 40)),
              Offstage(
                  offstage: widget.type != 'xgzf',
                  child: buildPasswordTextField()),
              SizedBox(height: 40),
              buildPasswordTextField1(),
              SizedBox(height: 20),
              buildPasswordTextField2(),
              SizedBox(height: 30),
              buildRegisterButton(context)
            ]),
      ),
    );
  }

  Widget buildPasswordTextField() {
    return TextFormField(
      // ignore: missing_return
      validator: (value) {
        RegExp pwd = RegExp(r'^[0-9]{6}$');
        if (!pwd.hasMatch(value) && widget.type == 'xgzf') {
          return '请输入6位数字密码';
        }
      },
      onSaved: (String value) => _oldPwd = value,
      obscureText: true,
      keyboardType: textInputType,
      maxLength: maxLength,
      decoration: InputDecoration(
        labelText: '旧密码',
        hintText: '请输入旧密码',
        contentPadding: EdgeInsets.all(10),
        prefixIcon: Icon(Icons.beenhere),
        border: OutlineInputBorder(
          borderSide: BorderSide(
            color: Theme.of(context).accentColor,
          ),
          borderRadius: BorderRadius.all(
            Radius.circular(24),
          ),
        ),
      ),
    );
  }

  Widget buildPasswordTextField1() {
    RegExp pwd;
    String hint;
    if ("xgmm" == widget.type || "wjmm" == widget.type) {
      pwd = RegExp(r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$');
      hint = '请输入6~12位字母数字组合密码';
    } else {
      pwd = RegExp(r'^[0-9]{6}$');
      hint = "请输入6位支付密码";
    }
    return TextFormField(
      // ignore: missing_return
      validator: (value) {
        if (!pwd.hasMatch(value)) {
          return hint;
        }
      },
      onSaved: (String value) => _password = value,
      obscureText: true,
      keyboardType: textInputType,
      maxLength: maxLength,
      decoration: InputDecoration(
        labelText: '密码',
        hintText: hint,
        contentPadding: EdgeInsets.all(10),
        prefixIcon: Icon(Icons.beenhere),
        border: OutlineInputBorder(
          borderSide: BorderSide(
            color: Theme.of(context).accentColor,
          ),
          borderRadius: BorderRadius.all(
            Radius.circular(24),
          ),
        ),
      ),
    );
  }

  Widget buildPasswordTextField2() {
    return TextField(
      controller: pwdController,
      keyboardType: textInputType,
      maxLength: maxLength,
      obscureText: true,
      decoration: InputDecoration(
        labelText: '确认密码',
        hintText: '请重新输入一次密码',
        contentPadding: EdgeInsets.all(10),
        prefixIcon: Icon(Icons.beenhere),
        border: OutlineInputBorder(
          borderSide: BorderSide(
            color: Theme.of(context).accentColor,
          ),
          borderRadius: BorderRadius.all(
            Radius.circular(24),
          ),
        ),
      ),
    );
  }

  Align buildRegisterButton(BuildContext context) {
    return Align(
      child: SizedBox(
        height: 45.0,
        width: MediaQuery.of(context).size.width,
        child: RaisedButton(
          child: Text(
            '下一步',
            style: TextStyle(color: Colors.white, fontSize: 18),
          ),
          color: Theme.of(context).accentColor,
          onPressed: () {
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
              FocusScope.of(context).requestFocus(FocusNode());
              if ("xgmm" == widget.type || "wjmm" == widget.type) {
                updatePwd();
              } else {
                updatePayPwd();
              }
            }
          },
          shape: StadiumBorder(
            side: BorderSide(color: Theme.of(context).accentColor),
          ),
        ),
      ),
    );
  }

  ///更新登录密码
  void updatePwd() {
    String pwd = pwdController.text;
    if (_password != pwd) {
      Toast.show('两次输入不一致');
      return;
    }
    CancelFunc cancelFunc = Toast.loading("操作中...");
    Map<String, String> params = Map();
    params['phone'] = widget.phone;
    params['password'] = pwd;
    Http.post(Api.URL_RESETPWD, params: params, successCallBack: (data) {
      Toast.show("操作成功");
      cancelFunc();
      Navigator.of(context).pop();
    }, errorCallBack: (msg) {
      Toast.show(msg);
      cancelFunc();
    });
  }

  ///更新支付密码
  void updatePayPwd() {
    String pwd = pwdController.text;
    if (_password != pwd) {
      Toast.show('两次输入不一致');
      return;
    }
    CancelFunc cancelFunc = Toast.loading("操作中...");
    Map<String, String> params = Map();
    if (widget.type == 'bdzf') {
      params['pwd'] = pwd;
      params['add'] = pwd;
    } else {
      params['oldPwd'] = _oldPwd;
      params['newPwd'] = pwd;
    }
    Http.post(Api.URL_WALLET_PWD, params: params, successCallBack: (data) {
      Toast.show("操作成功");
      cancelFunc();
      Navigator.of(context).pop();
    }, errorCallBack: (msg) {
      Toast.show(msg);
      cancelFunc();
    });
  }
}
